<template>
  <div id="loginweixin">
    <!-- 授权判断是否绑定手机号 -->
    <section class="bgsign">
      <!-- 背景图 -->
      <div class="sign">
        <div class="homepage">
          <img src="@/assets/two/new_logo.png" />
        </div>
      </div>
      <div class="verification">
        <div class="cation">
          <div class="phone_wrap">
            <img class="icon_phone" src="@/assets/two/icon_phone.png" />
            <input
              type="tel"
              pattern="[0-9]*"
              maxlength="11"
              oninput="value=value.replace(/[^\d]/g,'')"
              placeholder="请输入手机号码"
              v-model="phone"
              @blur="checkPhone(1)"
              @focus="checkph()"
              :class="{ errBorder: errMsg == 1 }"
            />
            <img
              class="clear-icon"
              src="@/assets/two/clear-icon.png"
              v-show="isShowPhone"
              @click="clearPhone"
            />
          </div>
          <span class="tips" v-show="errMsg1">*手机号格式错误</span>
          <span class="tips" v-show="empty1">*请输入手机号</span>

          <div class="box">
            <img class="icon_verify" src="@/assets/two/icon_verify.png" />
            <input
              type="number"
              v-model="code"
              oninput="if(value.length>6) value = value.slice(0,6)"
              @blur="checkCode()"
              @focus="checkPhone(1)"
              :class="{ errBorder: errMsg == 2 }"
              placeholder="请输入验证码"
              @keyup.enter.native="confirmBtn()"
              ref="phoneCodeInput"
            />
            <img
              class="clear-icon"
              style="margin-right:0.4rem;"
              src="@/assets/two/clear-icon.png"
              v-show="isShowCode"
              @click="clearCode"
            />
            <!-- disabled="tapclick" -->
            <button @click="get_code(1)">
              <span>{{ time }}</span>
            </button>
          </div>

          <!-- v-if="errMsg == 3" -->
          <p class="errMsg" v-if="errMsg == 3" @click="loginwx()">
            *该手机号已被绑定，请变更号码或
            <span>直接短信登录</span>
          </p>
          <span class="tips" v-show="errMsg2">*验证码错误</span>
          <span class="tips" v-show="empty2">*请输入验证码</span>
          <button
            id="loginBtn"
            :class="{active:phone.length==11 && code.length==6}"
            @click="confirmBtn()"
          >确定</button>
        </div>
      </div>
    </section>
  </div>
</template>
<script>
export default {
  name: '',
  components: {},
  data() {
    return {
      phone: '',
      code: '',
      sessionId: '',
      time: '获取验证码',
      errMsg: 0, //0:通过    1:手机号格式不对 2：验证码格式不对
      vipLevel: 0,
      person_message: null,
      tapclick: false, //获取验证是否可以点击
      cancel03: null,
      cancel04: null,
      cancel05: null,
      empty1: false,
      errMsg1: false,
      empty2: false,
      errMsg2: false,
      wxcode: '',
      phoneReg: /^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/,
      isShowPhone: false, //手机号清除图标
      isShowCode: false
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    // 清除手机号
    clearPhone() {
      this.phone = '';
    },
    clearCode() {
      this.code = '';
    },
    //  验证手机号   ///   验证手机号失焦点   ///  验证码获取焦点
    checkPhone() {
      setTimeout(() => {
        this.isShowPhone = false;
        this.isShowCode = true;
      }, 0);
      const str = /^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/;
      if (!str.test(this.phone)) {
        this.empty1 = false; //请输入
        this.errMsg1 = true; //格式错误
      }
      if (this.phone.length === 0) {
        this.empty1 = true; //请输入手机号
        this.errMsg1 = false;
      }
      if (str.test(this.phone) && this.phone.length != 0) {
        this.empty1 = false;
        this.errMsg1 = false;
      }
      if (this.code.length === 0 || this.code.length != 6 || this.code.length != 0) {
        this.empty2 = false;
        this.errMsg2 = false;
      }
    },
    // 获取验证码
    get_code(codeType) {
      let that = this;
      if (this.time != '重新获取' && this.time != '获取验证码') {
        return false;
      }
      const str = /^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/;
      if (this.phone.length === 0) {
        this.empty1 = true;
        this.errMsg1 = false;
        return false;
      }
      if (!str.test(this.phone)) {
        this.empty1 = false; //请输入
        this.errMsg1 = true; //格式错误
        return false;
      }
      if (str.test(this.phone) && this.phone.length != 0) {
        // 手机号满足条件发送验证码
        this.empty1 = false;
        this.errMsg1 = false;
      }
      if (codeType == 1) {
        that.$axios
          .get('/api/customer/VerifyMobile', {
            params: {
              mobile: that.phone
            }
          })
          .then(res => {
            if (res.data.code == 0) {
              that.getsmsCode();
            } else if (res.data.code == 1) {
              that.errMsg2 = false;
              this.errMsg2 = false;
              this.empty1 = false;
              this.empty2 = false;
              that.errMsg = 3;
              return false;
            }
          })
          .catch(err => {
            console.log(err);
          });
      } else {
        that.getsmsCode();
      }
      this.$refs.phoneCodeInput.focus();
    },
    //重新获取验证
    getsmsCode() {
      let that = this;
      let temp = 60;
      this.time = temp + 's';
      this.loopTime = setInterval(() => {
        temp -= 1;
        this.time = temp + 's';
        if (temp == 0) {
          clearInterval(this.loopTime);
          this.time = '重新获取';
        }
      }, 1000);
      //   获取验证码
      this.$axios(
        {
          method: 'get',
          url: '/api/customer/getsms',
          params: {
            mobile: that.phone
          }
        },
        {
          cancelToken: new that.$axios.CancelToken(function executor(c) {
            if (that.cancel03) that.cancel03();
            that.cancel03 = c;
          })
        }
      )
        .then(response => {
          if (response.data.code == 1001) {
            this.$toast(response.data.msg);
          }
          // if (response.data.code == 0) {}
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 绑定手机号
    confirmBtn() {
      if (this.phoneReg.test(this.phone) && this.code.length == 6) {
        //满足条件才去绑定手机号
        let that = this;
        let invitecode = this.$route.query.invitecode;
        invitecode = invitecode ? invitecode : '';
        that.$axios
          .post(
            '/api/customer/bindmobile',
            {
              mobile: this.phone,
              code: this.code,
              SessionId: this.$route.query.msg,
              InviteCode: invitecode
            },
            {
              cancelToken: new that.$axios.CancelToken(function executor(c) {
                if (that.cancel06 != null) {
                  that.cancel06();
                }
                that.cancel06 = c;
              })
            }
          )
          .then(response => {
            this.$toast(response.data.msg);
            if (response.data.code == 0) {
              /* this.$message({
                message: '',
                type: 'success',
                duration: 2000,
                offset: '400',
              }) */
              localStorage.setItem('user_id', response.data.data.accountId);
              localStorage.setItem('photo', response.data.data.headImgUrl);
              if(response.data.data.loginType == 2 && invitecode){
                localStorage.setItem('isInvitationUser', 1);  //是否为被邀请注册用户
              }
              this.headImgUrl = response.data.data.headImgUrl;
              // this.$getPower(response.data.data.vipLevel);
              // this.$router.push('/');
              location.replace('/');
            } else if (response.data.code == 4) {
              this.errMsg2 = true;
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    },
    // 验证验证码格式（失去焦点）
    checkCode() {
      setTimeout(() => {
        this.isShowCode = false;
      }, 0);
      if (this.code.length === 0) {
        this.empty2 = true;
        this.errMsg2 = false;
      } else if (this.code.length != 6) {
        this.empty2 = false;
        this.errMsg2 = true;
      }
    },
    // 手机号获取到焦点
    checkph() {
      this.empty1 = false;
      this.errMsg1 = false;
      this.isShowPhone = true;
    },
    //点击确定
    phone_login() {
      if (!(this.phone.length == 11)) {
        return (this.errMsg2 = false);
      }
      if (!(this.code.length == 6)) {
        return (this.errMsg2 = false);
      }
      let that = this;

      this.$axios
        .post(
          '/api/customer/smslogin',
          {
            Mobile: that.phone,
            Code: that.code
          },
          {
            cancelToken: new that.$axios.CancelToken(function executor(c) {
              if (that.cancel04) that.cancel04();
              that.cancel04 = c;
            })
          }
        )
        .then(response => {
          if (response.data.code == 0) {
            /*   this.$message({
              message: '登录成功！',
              type: 'success',
              duration: 2000,
              offset: '400',
            }) */
            // 存储 id
            localStorage.setItem('user_id', response.data.data.user_id);
            localStorage.setItem('headImgUrl', response.data.data.headImgUrl);
            // this.$router.push('/'); //首页
            location.replace('/');
          } else if (response.data.code == 1) {
            // 手机号
            this.errMsg2 = true;
            this.empty1 = false;
            this.empty2 = false;
          } else {
            // 验证码
            this.errMsg2 = true;
            this.empty1 = false;
            this.empty2 = false;
          }
          // this.$toast(response.data.msg);
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 跳转登录页面
    loginwx() {
      this.$router.push({ path: '/login',query:{sms:1} });
    }
  }
};
</script>
<style scoped lang='less'>
// 登陆
#loginweixin {
  width: 100%;
  height: 100vh;
  box-sizing: border-box;
  *,
  *:before,
  *:after {
    box-sizing: inherit;
  }
  .van-nav-bar__title {
    font-size: 0.426667rem;
    font-weight: 600;
    color: #222;
  }
  //   登录
  .bgsign {
    width: 100%;
    .active {
      //提交按钮
      background-color: #fd7f2c !important;
      color: #fff !important;
    }
    .sign {
      width: 100%;
      height: 6.04rem;
      background: url(../../assets/two/new_bg.png) no-repeat 0 -1.933333rem;
      background-size: 100% 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      .homepage {
        width: 1.88rem;
        height: 1.88rem;
        background: #fff;
        box-shadow: 0px 0px 19px 5px rgba(0, 0, 0, 0.1);
        border-radius: 0.4rem;
        img {
          width: 100%;
          height: 100%;
        }
      }
    }
    .verification {
      width: 100%;
      .cation {
        width: 100%;
        padding: 0 0.813333rem;
        .phone_wrap,
        .box {
          padding-bottom: 0.4rem;
          border-bottom: 1px solid #e5e5e5;
          display: flex;
          align-items: center;
          position: relative;
          .icon_phone,
          .icon_verify {
            vertical-align: middle;
            width: 0.333333rem;
            height: 0.44rem;
            margin-right: 0.386667rem;
          }
          .clear-icon {
            width: 0.413333rem;
            height: 0.413333rem;
          }
        }
        input[type='number'],
        input[type='tel'] {
          outline: none;
          border: 0;
          font-size: 0.4rem;
          width: 100%;
          height: 100%;
          background-color: transparent;
        }

        .tips {
          //提示手机号错误
          display: block;
          font-size: 0.32rem;
          line-height: 1.093rem;
          height: 1.093rem;
          letter-spacing: 0px;
          color: #ff0000;
        }

        .box {
          margin-top: 0.706667rem;
          > button {
            outline: none;
            width: 4.506667rem;
            font-size: 0.4rem;
            color: #ee7d2f;
            border: 0;
            background: transparent;
            border-left: 1px solid #e5e5e5;
          }
        }
        #loginBtn {
          outline: none;
          border: 0;
          width: 100%;
          margin-top: 1.773333rem;
          height: 1.226667rem;
          background-color: #b5b5b5;
          border-radius: 0.266667rem;
          font-size: 0.4rem;
          color: #fff;
        }
      }
    }
  }
  // 手机号已被绑定
  .errMsg {
    font-size: 0.32rem;
    font-weight: normal;
    font-stretch: normal;
    line-height: 1.093rem;
    height: 1.093rem;
    letter-spacing: 0px;
    color: #ff0000;
    span {
      color: #1779ff;
    }
  }
}
</style>